<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/9/18 9:35
 * Desc: 会员消息
 */
class Service_Api_Member_Message extends Contract_Api_Member_Message
{

    public function list(int $mid, array $params = array()): array
    {
        /**
         * @var int $page
         * @var int $pagesize
         * @var int $status
         */
        extract($params);

        $builder = DB::select('id', 'type', 'content', 'addtime', 'status',
            DB::expr('orderid AS order_id,product_typeid as product_type_id,productid as product_id'))
            ->from('message')
            ->where('memberid', '=', $mid)
            ->and_where('memberid', '>', 0);

        if (!empty($params['status'])) {
            $builder->where('status', '=', $status);
        }

        $total = $builder->execute()->count();

        if (!empty($page) && !empty($pagesize)) {
            $offset = St_Page::offset($page, $pagesize);
            $builder->offset($offset)->limit($pagesize);
        }

        $builder->order_by('addtime', 'desc');

        $list = $builder->execute()->as_array();

        return array(
            'total' => $total,
            'mid' => $mid,
            'list' => $list
        );
    }

    function viewed(int $mid, int $id): array
    {
        $message = ORM::factory('message', $id)
            ->where('memberid', '=', $mid);
        if (!$message->id) {
            throw new Exception('消息不存在');
        }
        $message->status = 1;
        $message->save();
        if ($message->saved()) {
            return array();
        } else {
            throw new Exception('保存失败');
        }
    }
}